import { v4 as uuidv4 } from 'uuid';
import md5 from 'md5';
import jwt from 'jsonwebtoken';
import config from '../config';

export default {
    // 判空
    isEmpty(value: any): boolean {
        return (
            value == null ||
            (typeof value === 'object' && Object.keys(value).length === 0) ||
            (typeof value === 'string' && value.trim().length === 0)
        );
    },
    // 验证邮箱
    validateEmail(email: string): boolean {
        if (email.length > 320) return false;
        const reg = /^[\w-.]+@([\w-]+\.)+[\w]{2,4}$/;
        return reg.test(email);
    },
    // 验证密码
    validatePassword(password: string): boolean {
        const reg = /^[a-zA-Z0-9$@!%*#.\-?&]{0,18}$/;
        return reg.test(password);
    },
    // 验证注册信息
    validateRegister({ email, password }: { email: string; password: string }): boolean {
        return this.validateEmail(email) && this.validatePassword(password);
    },
    // 验证登陆信息
    validateLogin({ email, password }: { email: string; password: string }): boolean {
        return this.validateEmail(email) && this.validatePassword(password);
    },
    // 生成激活码
    generateActivationCode(): string {
        return uuidv4();
    },
    // 生成 uuid
    generateuuid(): string {
        return uuidv4();
    },
    // 对比激活码
    compareActivationCode(code1: string, code2: string): boolean {
        if (code1 === code2) {
            return true;
        }
        return false;
    },
    // md5 加密
    md5(key: string): string | null {
        if (!key) {
            // 判空
            return null;
        }
        return md5(key);
    },
    /**
     *
     * @param key 未加密密码
     * @param encryption md5 加密密码
     * @returns Boolean
     * @desc 比较 md5 密码
     */
    compareMd5(key: string, encryption: string): boolean {
        const encryptrionKey = this.md5(key);
        if (encryptrionKey === encryption) {
            return true;
        }
        return false;
    },
    // 生成 token
    /**
     *
     * @param payload 应包含 id 和 email
     * @param expiresIn 过期时间
     * @returns token
     */
    generateToken(payload: any, expiresIn = 86400): string {
        return jwt.sign(payload, config.KEYS.secretOrKey, { expiresIn });
    },
};
